package com.cyw.common.utils;

import com.cyw.common.domain.common.PageWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.function.Function;

import static com.cyw.common.utils.BaseUtils.isNullThr;
import static com.cyw.common.utils.StreamUtils.propList;


/**
 * 分页相关转换工具类
 * @Author: cyw
 * @CreateTime: 2021年3月30日14:40:05
 **/
public class PageConvertUtils {

    public static <Element, Prop> List<Prop> convertList(PageWrapper<Element> pre, Function<Element, Prop> propExtractor) {
        return BaseUtils.isEmpty(pre) ? Lists.newArrayList() : propList(pre.getList(), propExtractor);
    }

    public static <Element, Prop> Page<Prop> convertPage(Page<Element> pre, Function<Element, Prop> propExtractor) {
        Page<Prop> page = new Page<>();

        isNullThr(pre, "非法请求参数");

        page.setPageNum(pre.getPageNum());
        page.setPageSize(pre.getPageSize());
        page.setTotal(pre.getTotal());
        page.setPages(pre.getPages());

        page.addAll(propList(pre.getResult(), propExtractor));
        return page;
    }

    public static <Element, Prop> PageInfo<Prop> convertPageInfo(PageInfo<Element> pre, Function<Element, Prop> propExtractor) {
        PageInfo<Prop> pageInfo = new PageInfo<>();

        isNullThr(pre, "非法请求参数");

        pageInfo.setPageNum(pre.getPageNum());
        pageInfo.setPageSize(pre.getPageSize());
        pageInfo.setTotal(pre.getTotal());
        pageInfo.setPages(pre.getPages());

        pageInfo.setList(propList(pre.getList(), propExtractor));
        return pageInfo;
    }

    public static <Element, Prop> PageWrapper<Prop> convertWrapper(Page<Element> page, Function<Element, Prop> propExtractor) {
        isNullThr(page, "非法请求参数");

        return PageWrapper.convert(page, propList(page.getResult(), propExtractor));
    }

    public static <Element, Prop> PageWrapper<Prop> convertWrapper(PageInfo<Element> pageInfo, Function<Element, Prop> propExtractor) {
        isNullThr(pageInfo, "非法请求参数");

        return PageWrapper.convert(pageInfo, propList(pageInfo.getList(), propExtractor));
    }

    public static <Element, Prop> PageWrapper<Prop> convertWrapper(PageWrapper<Element> pageWrapper, Function<Element, Prop> propExtractor) {
        isNullThr(pageWrapper, "非法请求参数");

        return PageWrapper.convert(pageWrapper, propList(pageWrapper.getList(), propExtractor));
    }

}
